var db;
if(!window.localStorage.todoList){
	db = [];	
}else{
	db = JSON.parse(window.localStorage.todoList);
}

var dbSave = function(){
	window.localStorage.todoList = JSON.stringify(db);

}

var dbClear = function(){
	window.localStorage.todoList = "";
	db = [];	
}

var TodoBox = React.createClass({
	getInitialState:function(){

		var _data = db;

		return {data:_data};
	},
	handleTodoSubmit:function(_data){
		if(this.state.handlingTag == 1){
			console.warn("last commit is running, please wait..")
		}
		db.push(_data);
		dbSave();
		this.setState({data: db});
	},
	handleTodoRemoveAll:function(){
		dbClear();
		this.setState({data: []});
	},
	render:function(){
		return <div className="todoList" ref="todoBox">
				<h1>TotoList</h1>		
			   <TodoForm ref="todoForm" onTodoSubmit={this.handleTodoSubmit} onTodoRemoveAll={this.handleTodoRemoveAll}/>
			   <TodoList data={this.state.data}/>
			   </div>
	}
});

var TodoForm = React.createClass({
    getInitialState: function() {
    	return {name: '', email: ''};
  	},
	handleChange: function(name,e) {
		var newState = {};
		console.log(e);
		newState[name] = e.target.value;

		this.setState(newState);
	},
  	handleSubmit:function(e){
  		e.preventDefault();

  		var _data = {
  			name:this.state.name.trim(),
  			email:this.state.email.trim()
  		}

  		this.props.onTodoSubmit(_data);

		this.setState({name: '' , email: ''});
  	},
	removeAll:function(){
		this.props.onTodoRemoveAll();
	},  	
	render:function(){
		return <div className="todoForm">
				<form className="commnetForm" onSubmit = {this.handleSubmit}>
					<label for="">Name:<input type="text" name="name" value={this.state.name} onChange={this.handleChange.bind(this,'name')}/></label>
					<label for="">Email:<input type="text" name="email" value={this.state.email} onChange={this.handleChange.bind(this,'email')}/></label>
					<input type="submit" value="保存"/>
					<span onClick={this.removeAll}>删除所有</span>
				</form>
			   </div>
	}
})

var Todo = React.createClass({
	deleteItem:function(){
		var _data = topEle.state.data;
		var _name = this.props.name
		_data.map(function(d,i){
			if(d.name == _name){
				_data.splice(i,1);
			}
		},_name);
		db = _data;
		topEle.setState({data:_data});
		dbSave();
		// console.log(e);
		// console.log();
	},
	render:function(){
		return <div classNmae="todo">
					<span>{this.props.name} </span>
					<span>{this.props.email} </span>
					<a className="todo-del" onClick={this.deleteItem}>delete</a>
			   </div>
	}
});

var TodoList = React.createClass({
	render:function(){
		var todoNodes = this.props.data.map(function(info){
			return <Todo name={info.name} email={info.email}></Todo>
		});
		return <div className="todoList">
				{todoNodes}
			   </div>
	}
})

var topEle = ReactDOM.render(
		<TodoBox/>,
		document.getElementById("container")
	);

console.log(topEle.refs.todoForm);